/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.antcloud.demo.antscheduler.nine1nine;

import java.util.Map;

import com.alibaba.fastjson.JSON;

import com.alipay.common.event.UniformEvent;
import com.alipay.common.event.UniformEventContext;
import com.alipay.common.event.UniformEventMessageListener;
import com.alipay.sofa.pay.facade.model.PayOrder;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author qian.lqlq
 * @version $Id: MqMessageListener.java, v 0.1 2018年09月06日 11:37 qian.lqlq Exp $
 */
public class MqMessageListener implements UniformEventMessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(MqMessageListener.class);

    @Override
    public void onUniformEvent(UniformEvent uniformEvent,
                               UniformEventContext uniformEventContext) throws Exception {
        /* get TOPIC, EVENTCODE and payload from the message instance */
        final String topic = uniformEvent.getTopic();
        final String eventcode = uniformEvent.getEventCode();
        final String id = uniformEvent.getId();
        final PayOrder payOrder = (PayOrder) uniformEvent.getEventPayload();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Receive a message, TOPIC [{}] EVENTCODE [{}] id [{}] payload [{}]",
                new Object[] { topic, eventcode, id, JSON.toJSONString(payOrder) });
        }
        try {
            String userId = payOrder.getTargetUid();
            Map<String, PushMsg> msgMap = Maps.newHashMap();
            msgMap.put(userId, new PushMsg(userId, PushMsgTypeEnum.TRANSFER, payOrder));
            WebSocketServer.sendMessage(msgMap);
        } catch (Exception e) {
            LOGGER.error("Process a message, failure. TOPIC [{}] EVENTCODE [{}] id [{}] error {}",
                new Object[] { topic, eventcode, id, e.getMessage() }, e);
            /* When any exception is thrown, the message is re-delivered later. */
            throw e;
        }

    }
}